package utils.global.utils;

import cn.hutool.core.io.file.FileWriter;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.annotation.ExcelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;


public class ApiExportUtils {

    public static List<ExcleData> getListApis(String prefix) {
        RequestMappingHandlerMapping mappingHandlerMapping = ContextUtils.getBean(RequestMappingHandlerMapping.class);
        Map<RequestMappingInfo, HandlerMethod> handlerMethods = mappingHandlerMapping.getHandlerMethods();
        HashSet<ExcleData> result = new HashSet<>();
        handlerMethods.keySet().forEach(e -> {
            Set<String> patterns = e.getPatternsCondition().getPatterns();
            result.addAll(patterns.stream().map(item -> {
                item = clear(item);
                if (prefix.endsWith("/")) {
                    item = prefix + item.substring(1);
                } else {
                    item = prefix;
                }
                return new ExcleData(item);
            }).collect(Collectors.toList()));
        });
        return new ArrayList<>(result);
    }

    private static String clear(String path) {
        path = path.replaceAll("(/\\{[a-zA-Z]*})", "");
        return path;
    }

    public static void getApisToExcle(String prefix, HttpServletResponse response) throws IOException {
        List<ExcleData> listApis = getListApis(prefix);
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("测试", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), ExcleData.class).sheet("模板").doWrite(listApis);
    }

    public static void getApisToExcle(String prefix, String filePath) throws IOException {
        List<ExcleData> listApis = getListApis(prefix);
        EasyExcel.write(filePath, ExcleData.class).sheet("模板").doWrite(listApis);
    }

    public static void getApisToTxt(String prefix, String filePath) throws IOException {
        File file = new File(filePath);
        if (!file.exists()) {
            boolean newFile = file.createNewFile();
            if (!newFile) {
                throw new RuntimeException(filePath + ": 创建失败");
            }
        }
        List<ExcleData> listApis = getListApis(prefix);
        FileWriter fileWriter = new FileWriter(file.getAbsolutePath());
        fileWriter.writeLines(listApis.stream().map(ExcleData::getApi).collect(Collectors.toList()));
    }

    @Data
    @AllArgsConstructor
    private static class ExcleData {
        @ExcelProperty("api")
        private String api;
    }

}
